const express = require("express")
const u = express.Router();
const uuid= require("uuid")
const fs = require('fs')
const { verifyToken } = require("../middlewares/Auth");
const multer  = require('multer')
const moment = require('moment');
// 引入文件上传配置
const MulterConfig =require('../utils/MulterConfig');
const pool = require("../pool/DatabaseConnect");
let BaseUrl = 'http://localhost:3050/public/upload/'
// 配置多文件上传、单文件上传、上传数量等等
/**      **************      **/
let  upload  = MulterConfig.fields([{name:'file',maxCount:3}])

u.post('/file',(req,res,next)=>{

  upload(req,res,function(err) {
    // 错误捕捉
    if (err instanceof multer.MulterError) {
      // 发生错误
     res.send({code:201,msg:'文件上传出错！'})
    } else if (err) {
      // 发生错误
     res.send({code:201,msg:'文件上传出错！'})
    }

    // 单文件 [{}]      多文件 [{1},{2},{3}]
    let FileArr = req.files.file
    console.log(FileArr)
    let First = `INSERT INTO ali_image VALUES `;
     // 生成图片ID
     let code = Math.floor(Math.random() * 9000)+1000
    // 一切都好
    if(req.body.imgage_code){
      code = req.body.imgage_code
    }else{
      code = Math.floor(Math.random() * 9000)+1000
    }
    //  拿到 用户id
    let user_id = 5
    //  生成图片唯一ID
    let imgid = uuid.v1()
    // 上传时间
    let date = moment().format("YYYY年MM月DD日HH点mm分ss秒"); 
   for(let i = 0;i<FileArr.length;i++){
     if(FileArr.length == 1){
      First += `("${imgid}",${code},"${FileArr[0].fieldname}","${FileArr[0].originalname}",
        "${FileArr[0].encoding}","${FileArr[0].mimetype}","${FileArr[0].destination}","${FileArr[0].filename}","${FileArr[0].path}","${FileArr[0].size}",${user_id},"${date}")`
    }else if(i<FileArr.length-1){
      First += `("${imgid}",${code},"${FileArr[i].fieldname}","${FileArr[i].originalname}",
        "${FileArr[i].encoding}","${FileArr[i].mimetype}","${FileArr[i].destination}","${FileArr[i].filename}","${FileArr[i].path}","${FileArr[i].size}",${user_id},"${date}"),`
    }else{
      First += `("${imgid}",${code},"${FileArr[i].fieldname}","${FileArr[i].originalname}",
        "${FileArr[i].encoding}","${FileArr[i].mimetype}","${FileArr[i].destination}","${FileArr[i].filename}","${FileArr[i].path}","${FileArr[i].size}",${user_id},"${date}")`
    }
   }
  pool.query(First,(err,result)=>{
    if(err){
      next(err)
      return
    }
    console.log(result)
    if(result.affectedRows>0){
      res.send({code:200,msg:'上传成功！',image_code:code,imgid:imgid,fieldname:FileArr[0].filename,})
    }else{
      res.send({code:201,msg:'文件上传失败！'})
    }
  })

  })

})

// 文件删除
u.post('/delfile',(req,res,next)=>{
  // 删除需要文件ID
  let BasePath ='public/upload/'
  let sql =`SELECT filename FROM  ali_image WHERE image_id = ?` 
  let imgid = req.body.imgid
  let delsql =`DELETE  FROM ali_image WHERE image_id = ?`
  // console.log(date)
  pool.query(sql,imgid,(err,result)=>{{
    if(err){
      next(err)
      return
    }
    
    if(result.length !=0){
      console.log(`${BasePath}${result[0].filename}`)
      fs.unlink(`${BasePath}${result[0].filename}`,function(err){
        if(err){
          res.send({code:201,msg:err})
          return
        }else{
          pool.query(delsql,imgid,(err,result)=>{
            if(err){
              next(err)
              return
            }
            if(result.affectedRows>0){
              res.send({code:200,msg:'文件删除成功！'})
            }else{
              res.send({code:201,msg:'文件删除失败！'})
              return
            }
          })
        }
      })
    }else{
      res.send({code:201,msg:'文件删除失败，文件不存在！'})
    }


  }})


})


/**      **************      **/
 module.exports = u;
